package cate.game.role.farm.adventure;

import cate.common.table.d.GDFunc;
import cate.common.table.d.GDOperation;
import cate.common.table.farm.adventure.row.AdventureCharpterRow;
import cate.game.client.msg.MergeMsgSender;
import cate.game.play.proce.play.PlayPO;
import cate.game.play.vo.PlayReportVO;
import cate.game.res.MixRes;
import cate.game.role.Role;
import cate.game.role.farm.adventure.msg.AdventureDataResp;
import cate.game.role.farm.adventure.msg.AdventureResultResp;
import cate.game.role.farm.cache.AbstractCacheFarmFTC;
import easy.java.dev.note.NoteClass;
import easy.java.practice.errorcode.EcResult;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

@NoteClass("主线挑战FTC")
public class AdventureCacheFTC extends AbstractCacheFarmFTC<Adventure> {
    /**
     * 当前挑战的战斗关卡模板
     */
    private final AdventureCharpterRow tpl;

    public AdventureCacheFTC(Role role, AdventureCharpterRow tpl, byte posNum) {
        super(GDFunc.ADVENTURE, role.getGame());
        setup(role);
        this.tpl = tpl;
        super.posNum = posNum;
    }

    @Override
    protected Adventure po(Role role) {
        return role.getFarm().adventure;
    }

    @Override
    protected boolean hasNext(Role role, PlayPO playPO) {
        return StringUtils.isNotBlank(tpl.getInsCode((byte) (posNum + 1)));
    }

    @Override
    protected EcResult<Void> challengeNext(Role role, byte nextPos) {
        return po(role).doChallenge(tpl, nextPos);
    }

    @Override
    protected void handleBefore(Role role, PlayPO playPO) {
        // DO NOTHING
    }

    @Override
    protected void handleFinish(Role role, PlayPO playPO, boolean win, boolean next, List<PlayPO> caches) {
        Adventure po = po(role);
        MergeMsgSender sender = new MergeMsgSender();
        List<PlayReportVO> reports = new ArrayList<>();
        for (PlayPO play : caches) {
            reports.add(new PlayReportVO(play));
        }
        MixRes reward = null;
        if (win && !next) {
            po.changeCombatIdPassed(tpl.id);
            role.log.setOperation(GDOperation.ADVENTURE_CHALLENGE);
            reward = po.buildReward();
            reward.addList(new MixRes(tpl.sectionResource));
            reward.add(role, sender);
            role.log.clearOperation();
            role.getHistory().action.adventurePass();
            role.send(new AdventureDataResp(role));
        }
        AdventureResultResp result = new AdventureResultResp(tpl.id, win, reward);
        result.over = !next;
        result.reports = reports;
        role.sendNow(result);
        sender.send(role, true);
    }
}
